window.onload = function() {
  //预先加载大图，避免后面鼠标移入后显示大图时再去请求资源，影响体验
  new Image().src = "image/001_big.jpg";
  new Image().src = "image/002_big.jpg";
  new Image().src = "image/003_big.jpg";
  new Image().src = "image/004_big.jpg";
  new Image().src = "image/005_big.jpg";

  // 获取dom
  const smallbox = document.querySelector("#box .smallbox"); //小图片box
  const bigbox = document.querySelector("#box .bigbox"); //大图片box
  const smallimg = smallbox.querySelector(".smallimg"); //小图片
  const bigimg = bigbox.querySelector(".bigimg"); //大图片
  const zoom = document.querySelector(".zoom"); // 移动小图
  const itemImg = document.querySelectorAll("#box .item img"); // 底部小图列表

  // 给每个小图片添加onmouseenter事件
  for (let i = 0, len = itemImg.length; i < len; i++) {
    itemImg[i].onmouseenter = function() {
      itemImg[i].removeAttribute("class", "borderhover");
      var imgSrc = this.src;
      smallimg.src = imgSrc;
      bigimg.src = `image/00${i + 1}_big.jpg`;
      itemImg.forEach(i => (i.className = ""));
      itemImg[i].setAttribute("class", "borderhover");
    };
  }

  //鼠标移入事件
  smallbox.onmouseenter = event => {
    // 第一步: 显示dom用于计算
    zoom.style.display = "block";
    bigbox.style.display = "block";
    // 第二步: 计算zoom可移动最大值
    let maxX = smallbox.offsetWidth - zoom.offsetWidth;
    let maxY = smallbox.offsetHeight - zoom.offsetHeight;
    // 第三步: 计算放大倍数
    var scale = bigimg.offsetWidth / smallimg.offsetWidth;

    //第四步: 鼠标在内部移动的时候,动态改变zoom的位置
    var ev = event || window.event;

    this.onmousemove = event => {
      //鼠标到可视化窗口左边的距离减去小图遮罩层的一半宽度则为zomm的left的值，同理可以求top的值
      zoom.style.left = event.clientX - zoom.offsetWidth / 2 + "px";
      zoom.style.top = event.clientY - zoom.offsetHeight / 2 + "px";
      // 实现紧贴着边框效果
      if (zoom.offsetLeft <= 0) {
        zoom.style.left = 0;
      }

      if (zoom.offsetTop <= 0) {
        zoom.style.top = 0;
      }

      if (zoom.offsetLeft >= maxX) {
        zoom.style.left = maxX + "px";
      }

      if (zoom.offsetTop >= maxY) {
        zoom.style.top = maxY + "px";
      }

      //zoom小遮罩层left的值乘以图片之间的放大倍数，则为右边大图片的left偏移值，top同理
      bigimg.style.left = "-" + zoom.offsetLeft * scale + "px";
      bigimg.style.top = "-" + zoom.offsetTop * scale + "px";
    };
  };

  //鼠标移出事件
  smallbox.onmouseleave = () => {
    bigbox.style.display = "none";
    zoom.style.display = "none";
    this.onmousemove = null;
  };
};
